package com.dailyblue.project.estate.pet.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dailyblue.project.estate.commons.bean.Pet;
import com.dailyblue.project.estate.commons.handler.PetException;
import com.dailyblue.project.estate.commons.mapper.PetMapper;
import com.dailyblue.project.estate.commons.util.DateUtil;
import com.dailyblue.project.estate.commons.util.JsonResult;
import com.dailyblue.project.estate.commons.util.ResultTool;
import com.dailyblue.project.estate.pet.service.PetService;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PetServiceImpl extends ServiceImpl<PetMapper, Pet> implements PetService {
    @Resource
    private PetMapper petMapper;

    @Override
    public JsonResult addPet(Pet pet) {
        boolean b = save(pet);
        if (!b) {
            throw new PetException("添加宠物失败");
        }
        return ResultTool.success("success");
    }

    @Override
    public JsonResult findOnePet(String PetId) {
        Pet pet = getById(PetId);
        return ResultTool.success(pet);
    }

    @Cacheable(cacheNames = "findAllPets")
    public JsonResult findAllPets() {
        List<Pet> list = list();
        return ResultTool.success(list);
    }

    @CacheEvict(cacheNames = "findAllPets", allEntries = true)
    public JsonResult deletePet(String PetId) {
        boolean b = removeById(PetId);
        if (b) {
            return ResultTool.success("删除成功");
        }
        return ResultTool.fail(201, "删除失败");
    }

    @CacheEvict(cacheNames = "findAllPets", allEntries = true)
    public JsonResult updatePet(Pet pet) {
        UpdateWrapper<Pet> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", pet.getId());
        updateWrapper.set("picture", pet.getPicture());
        updateWrapper.set("owner_id", pet.getOwnerId());
        updateWrapper.set("owner_name", pet.getName());
        updateWrapper.set("color", pet.getColor());
        updateWrapper.set("remark", pet.getRemark());
        updateWrapper.set("update_time", DateUtil.nowDate());
        updateWrapper.set("adopt_time", DateUtil.nowDate());
        int i = petMapper.update(updateWrapper);
        if (i <= 0) {
            return ResultTool.fail(201, "更新失败");
        }
        return ResultTool.success("更新成功");
    }
}
